package com.example.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.common.utils.jwt.PassToken;
import com.example.sys.entity.User;
import com.example.sys.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

import static java.nio.charset.StandardCharsets.UTF_8;

public class JwtAuthenticationInterceptor implements HandlerInterceptor{

    @Autowired
    UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws IOException {
        // 从 http 请求头中取出 token
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查是否有passToken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","500");
        jsonObject.put("msg","令牌无效，请重新登录");
        // 执行认证
        if (token == null) {
            jsonObject.replace("msg","用户无效，请重新登录");
            response.getOutputStream().write(jsonObject.toJSONString().getBytes(UTF_8));
            return false;
        }
        //设置token过期时间
        if(System.currentTimeMillis() - JWT.decode(token).getIssuedAt().getTime()>72000000){
            jsonObject.replace("msg","登录过期，请重新登录");
            response.getOutputStream().write(jsonObject.toJSONString().getBytes(UTF_8));
            return false;
        }
        System.out.println(System.currentTimeMillis());
        System.out.println(JWT.decode(token).getIssuedAt().getTime());
        System.out.println(System.currentTimeMillis() - JWT.decode(token).getIssuedAt().getTime());
        // 获取 token 中的 username
        String userId;
        try {
            userId = (JWT.decode(token).getAudience().get(0));
        } catch (JWTDecodeException j) {
            jsonObject.replace("msg","401");
            response.getOutputStream().write(jsonObject.toJSONString().getBytes(UTF_8));
            return false;
        }
        
        User user = userMapper.selectById(userId);
        if (user == null) {
            jsonObject.replace("msg","用户不存在，请重新登录");
            response.getOutputStream().write(jsonObject.toJSONString().getBytes(UTF_8));
            return false;
        }
        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            response.getOutputStream().write(jsonObject.toJSONString().getBytes(UTF_8));
            return false;
        }
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
